package gov.jslt.app.plugin.alipay;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.alipay.sdk.app.AuthTask;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import gov.jslt.app.tool.SignUtils;
import gov.jslt.app.vo.AuthResult;

public class AlipayLogin extends CordovaPlugin {

	// 商户PID
	public static final String PARTNER = "2088221838089771";
	// 商户收款账号
	public static final String SELLER = "jsstzdfswj@163.com";
	// 商户私钥，pkcs8格式
	public static final String RSA_PRIVATE = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMn1vI+/JmG92i3fvLVJ6/myTcUzLzf1KWsbQhsRjQOvstN+5l/cLUTUJs+IP2iUw6jSj8dgcUTRGlajGVPQPi7bmLUDXiLrGekNv17SfOetNrUwvFtr+Fu/TohbYFccwO6aNgGun6QOtNescGPGo1eBVP7HDic+EclhfCofIkkzAgMBAAECgYAIYQCcuiJ+haDqrFCo+NMofeRKHTCFUs+QGQZqFxVRpNV3ftlR+tGJ/H9Ltuxii2F+vJWogPDSGRbNp2CioI4j0o/wpTTfgWHrsLhq+nucWSvQytUBUaHAcOQ8bMgWy+c2/8rKtAY20sUHwKSCeamdI2k6tiiqd3yuax2U8kEnCQJBAP16k4FVhjDVGNceodUGTKpXM9EagB5M8dbE0yXfQhH6zXLZDXTuDniiEZwKm7zrp+OemJ8OnUiPiQ1T5DHLWpUCQQDL9/rMLUO6yylozQSmOQu7ZWSwt2c/cimKstKVNWxqhpX+/dBGyePUChABHseNDTHros3IBYF4jgd62pd6duqnAkEAyRwgviO59TKNo9gE9DwsRZYsYYJSFjhcRFcjY8双击查看原图3s4LhUya9aQOzT1hFVoBWHHsYZcqZkA1ICXpyi4+RheexQJBAJS6oho392dBtVRCCt3aQv/Gk4F4esT8zeXhN0Sty双击查看原图XvasxS6ZEJQRMlJey0vDD1+vOzZbLWlmx3WB52rZQ4kCQQDMipu08oO1FZBycV+FxU9EcYhwkuF4BMORIuwaaRjLNYc/335pBVP+FUBoj98xvUp0lA5Meq1HhOahF5MaOA2I";
	// 支付宝公钥
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB";

	private static final int SDK_AUTH_FLAG = 1;

	private CallbackContext callbackContext = null;
	public boolean result = false;
	private JSONObject returnInfo;
	private JSONObject dataObject;

	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
		if ("alipayLogin".equals(action)) {
			return alipayLogin(action, args, callbackContext);
		}
		return false;
	}

	public boolean alipayLogin(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
		try {
			this.callbackContext = callbackContext;
			// 授权信息
			String info = getAuthInfo();
			// 对授权信息做签名
			String sign = sign(info);
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
			// 完整的符合支付宝授权规范的参数信息
			final String authInfo = info + "&sign=\"" + sign + "\"&" + getSignType();

			Runnable authRunnable = new Runnable() {
				@Override
				public void run() {
					// 构造AuthTask 对象
					AuthTask authTask = new AuthTask(cordova.getActivity());
					// 调用授权接口，获取授权结果
					String result = authTask.auth(authInfo);
					Message msg = new Message();
					msg.what = SDK_AUTH_FLAG;
					msg.obj = result;
					mHandler.sendMessage(msg);
				}
			};

			// 必须异步调用
			Thread authThread = new Thread(authRunnable);
			authThread.start();
			return true;
		} catch (Exception e) {
			returnInfo = new JSONObject();
			returnInfo.put("code", "1");
			returnInfo.put("msg", "支付宝登录失败:" + e.getMessage());
			callbackContext.error(returnInfo);
		}
		return false;
	}

	@Override
	public void onDestroy() {

		super.onDestroy();
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			dataObject = new JSONObject();
			returnInfo = new JSONObject();
			switch (msg.what) {
			case SDK_AUTH_FLAG: {
				AuthResult authResult = new AuthResult((String) msg.obj);
				// 支付宝返回此次授权结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = authResult.getResult();
				String resultAuthCode = authResult.getAuthCode();
				String resultOpenId = authResult.getAlipayOpenId();
				String resultStatus = authResult.getResultStatus();

				// 判断resultStatus 为“9000”且result_code
				// 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
				try {
					if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
						returnInfo.put("code", "0");
						returnInfo.put("msg", "支付宝登录成功");
					} else {
						returnInfo.put("code", "1");
						returnInfo.put("msg", "支付宝登录失败");
					}
					dataObject.put("resultInfo", resultInfo);
					returnInfo.put("data", dataObject);
					callbackContext.success(returnInfo);
				} catch (Exception e) {

				}
				break;
			}
			default:
				break;
			}
		};
	};

	public String getAuthInfo() {
		String app_id = "2016062401552390";
		String pid = "2088221838089771";
		String target_id = UUID.randomUUID().toString();

		// 服务接口名称， 固定值
		String authInfo = "apiname=\"com.alipay.account.auth\"";

		// 商户签约拿到的app_id，如：2013081700024223
		authInfo += "&app_id=" + "\"" + app_id + "\"";

		// 商户类型标识， 固定值
		authInfo += "&app_name=\"mc\"";

		// 授权类型，授权常量值为"AUTHACCOUNT", 登录常量值为"LOGIN"
		authInfo += "&auth_type=\"AUTHACCOUNT\"";

		// 业务类型， 固定值
		authInfo += "&biz_type=\"openservice\"";

		// 商户签约拿到的pid，如：2088102123816631
		authInfo += "&pid=" + "\"" + pid + "\"";

		// 产品码， 固定值
		authInfo += "&product_id=\"WAP_FAST_LOGIN\"";

		// 授权范围， 固定值
		authInfo += "&scope=\"kuaijie\"";

		// 商户标识该次用户授权请求的ID，该值在商户端应保持唯一，如：kkkkk091125
		authInfo += "&target_id=" + "\"" + target_id + "\"";

		// 签名时间戳
		authInfo += "&sign_date=" + "\"" + getSignDate() + "\"";

		return authInfo;

	}

	/**
	 * sign the order info. 对授权信息进行签名
	 * 
	 * @param content
	 *            待签名授权信息
	 */
	public String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}

	/**
	 * get the sign time. 获取当前签名时间
	 * 
	 */
	public String getSignDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
		return format.format(new Date());
	}
}
